import React from 'react';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import { Link } from 'react-router';

import { product as ProductConfig } from '../config/Common';
import { pageSize } from '../config/Common';

import * as UserActions from '../actions/UserActions';
import * as MarketActions from '../actions/MarketActions';
import * as ProductActions from '../actions/ProductActions';

import {
  TabbedArea,
  TabPane
} from 'react-bootstrap';
                    
import Pager from '../components/Pager';
import DialogCommon from '../components/DialogCommon';
import DialogAlert from '../components/dialog/DialogAlert';
import Market from '../components/Market';
import Product from '../components/Product';
import Container from '../components/Container';

class ProductApp extends React.Component {

  constructor () {
    super(); 

    this.state = {
       dialogVisiable : false,
       dialogTitle : "",
       dialogContent : <div>系统提示</div>,
       dialogButton : null,

       shortPageIndex : 1,
       longPageIndex : 1,
       selectedTabKey : 1
    }; 
  }

  static propTypes = {
    product: React.PropTypes.object.isRequired,
    dispatch: React.PropTypes.func.isRequired
  }

  fetchProduct (){
    let dataParam = {
        start : this.pageIndex, 
        limit : 1000,
        bossStatus : ProductConfig.productStatus.all,
        bossType: ProductConfig.productType.all
    };
    this.props.productAction.fetchProduct(dataParam);
  }

  componentDidMount(){

    let { product, market } = this.props;
    if (market.market_status !== 1 ) {
      this.props.marketAction.fetchMarket();
    }
    if (product.product_status !== 1) {
      this.fetchProduct();  
    }
  }

  filterProductByType(){
    let { product } = this.props;
    let shortProduct, longProduct = null;

    if (product && product.results && product.results.length > 0) {
        shortProduct = []; 
        longProduct = [];
        for(let i = 0, len = product.results.length; i< len; i++){
            let productItem = product.results[i];
            if (productItem.status != ProductConfig.productStatus.noSign 
              && productItem.status!="") {
              continue;
            }
            if (productItem.gstype == ProductConfig.productType.short) {
              shortProduct.push(productItem);
            }else{
              longProduct.push(productItem);
            }
        }

        let { shortPageIndex, longPageIndex } = this.state;

        shortProduct = shortProduct.slice(0, (shortPageIndex) * pageSize);
        longProduct = longProduct.slice(0, (longPageIndex) * pageSize);
    }
    
    return { shortProduct, longProduct };
  }

  getResultLabel(data, msg){
    let result  = (data && data.length === 0) ? msg : "加载中";
    return result;
  }

  getShortPageEnabled(shortProduct){
    let shortPageEnabled = false;
    let pageTotalCount = (this.state.shortPageIndex) * pageSize;
    if(shortProduct && shortProduct.length >= pageTotalCount){
      shortPageEnabled = true;
    }
    return shortPageEnabled;
  }

  getLongPageEnabled(longProduct){
    let longPageEnabled = false;
    let pageTotalCount = (this.state.longPageIndex) * pageSize;
    if(longProduct && longProduct.length >= pageTotalCount){
      longPageEnabled = true;
    }
    return longPageEnabled;
  }

  onShortPageClick(){
    let pIndex = this.state.shortPageIndex;
    this.setState({
      shortPageIndex : pIndex + 1
    });
  }

  onLongPageClick(){
    let pIndex = this.state.longPageIndex;
    this.setState({
      longPageIndex : pIndex + 1
    });
  }

  componentDidUpdate(){
    let { product } = this.props;
    if (product) {
      let { product_sign_status = 0, message = "" } = product;

      product.product_sign_status = 0;

      if (product_sign_status === -1) {
          let dialogHeader = `系统提示`;
          let dialogContent  = <DialogAlert message={message}/>
          this.setState({
            dialogContent : dialogContent,
            dialogVisiable : true,
            dialogTitle : dialogHeader,
            dialogButton : [{
               text : "确定",
               style : "default"
            }]
          });
      }else if(product_sign_status === 1){
        this.props.userAction.fetchUser();
      }
    }
  }

  handleDialogHide(){
    this.setState({
       dialogVisiable : false
    });
  }

  handleTabSelect(index){
    this.setState({
      selectedTabKey : index
    });
  }

  render() {
    let { market, user, history, product } = this.props;
    let { shortProduct, longProduct } = this.filterProductByType();

    let shortPageEnabled = this.getShortPageEnabled(shortProduct);
    let longPageEnabled = this.getLongPageEnabled(longProduct);

    return (
          <Container 
              isGoBack={false} 
              isHeader={true} 
              isHeaderMessage={true}
              isFooter={true} 
              footerIndex={0} 
              headerTitle={"找策略"}>

               <Market markets={market.results} />

               <div className="product-container">
                  <TabbedArea activeKey={this.state.selectedTabKey} onSelect={ this.handleTabSelect.bind(this) }>
                    <TabPane eventKey={1} tab="短线策略">
                      {
                        product.product_status === 0 && shortProduct && shortProduct.length === 0?
                        <div className="text-center padding-lg">
                          { product.message }
                        </div> 
                        :
                        shortProduct && shortProduct.length > 0 ?
                        <Product 
                            products={ shortProduct } 
                            productType={ ProductConfig.productType.short } 
                            productStatus = { ProductConfig.productStatus.noSign} 
                            user={ user } 
                            history = { history }
                            productAction={ this.props.productAction }/>
                        :
                        <div className="text-center padding-lg">
                          { this.getResultLabel(shortProduct,`你已关注完所有短线策略`) }
                        </div>
                      }

                      {
                        shortPageEnabled || (shortProduct && shortProduct.length > 0)?
                        <Pager 
                          enabled = {shortPageEnabled}
                          status = {product.product_status}
                          onPageClick = {this.onShortPageClick.bind(this)}>
                          点击加载更多
                        </Pager>
                        :null
                      }

                    </TabPane>

                    <TabPane eventKey={2} tab="中线策略">
                        {
                          product.product_status === 0 && longProduct && longProduct.length === 0?
                          <div className="text-center padding-lg">
                            {product.message}
                          </div> 
                          :
                          longProduct && longProduct.length > 0 ?
                          <Product 
                            products={ longProduct } 
                            productType={ ProductConfig.productType.long } 
                            productStatus = { ProductConfig.productStatus.noSign} 
                            user={ user } 
                            history = { history }
                            productAction={ this.props.productAction }/>
                          :
                          <div className="text-center padding-lg">
                            { this.getResultLabel(longProduct, `你已关注完所有中线策略`) }
                          </div> 
                        }

                        {
                          longPageEnabled || (longProduct && longProduct.length > 0)?
                          <Pager 
                            enabled = {longPageEnabled}
                            status = { product.product_status }
                            onPageClick = {this.onLongPageClick.bind(this)}>
                            点击加载更多
                          </Pager>
                          :null
                        }
                    </TabPane>
                  </TabbedArea>
               </div>
               <DialogCommon 
                  title={ this.state.dialogTitle } 
                  content={ this.state.dialogContent } 
                  buttons = { this.state.dialogButton }
                  visiable={ this.state.dialogVisiable } 
                  onHide = { this.handleDialogHide.bind(this) }/>
          </Container>
    );
  }
}

export default connect(state => ({
    product: state.product,
    market : state.market,
    user: state.user
}), dispatch => ({
    marketAction: bindActionCreators(MarketActions, dispatch),
    productAction: bindActionCreators(ProductActions, dispatch),
    userAction: bindActionCreators(UserActions, dispatch)
}))(ProductApp);
